package com.yonyou.wdt.utils;

import com.google.gson.Gson;
import com.yonyou.wdt.entity.QueryDto;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author nishch
 * @version 1.0
 * @date 2020/3/11
 * @des 自建应用获取token信息
 */
@Component
public class SelfBuildToken {

    @Value("${yonyou.getTokenUrl}")
    private String openApiUrl;
    
    public String createToken(QueryDto dto) throws Exception {
        String token = null;
        int expire = 5400;
        Map<String, Object> params = new HashMap<String, Object>();
        // 除签名外的其他参数
        params.put("appKey", dto.getAppKey());
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        // 计算签名
        String signature = SignHelper.sign(params, dto.getAppSecret());
        params.put("signature", signature);
        String responseString = RequestTool.doGet(dto.getTokenUrl() + openApiUrl, params);
        Gson gson = new Gson();
        Map result = gson.fromJson(responseString, Map.class);
        if (ResultCode.SUCCESS.getIndex().equals(result.get(ResultCode.SUCCESS.getName()))) {
            Map<String, Object> tokenInfo = (Map<String, Object>) result.get("data");
            token = (String) tokenInfo.get("access_token");
            String[] expires = String.valueOf(tokenInfo.get("expire")).split("\\.");
            expire = Integer.parseInt(expires[0]);
            RedisUtils.set("Token:" + dto.getTenantId(), token, expire);
        } else {
            return "";
            // throw new Exception("获取token失败");
        }
        return token;
    }

}
